package com.aiapphub.BaseCode.controller;

import com.aiapphub.BaseCode.common.ResponseResult;
import com.aiapphub.BaseCode.entity.Role;
import com.aiapphub.BaseCode.service.RoleService;
import com.aiapphub.SystemCode.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 角色管理控制器
 */
@RestController
@RequestMapping("/admin/acl/role")
public class RoleController {

    private static final Logger log = LoggerFactory.getLogger(RoleController.class);

    @Autowired
    private RoleService roleService;
    
    @Autowired
    private UserService userService;

    /**
     * 获取角色分页列表
     */
    @GetMapping("/{page}/{limit}")
    public ResponseResult getPageList(@PathVariable Integer page, 
                                    @PathVariable Integer limit, 
                                    @RequestParam(required = false) Map<String, Object> params) {
        // 打印当前用户信息
        String currentUserId = userService.getCurrentUserId();
        log.info("当前用户ID: {}", currentUserId);
        
        // 打印更详细的用户信息
        if (userService.isUserLoggedIn()) {
            log.info("当前登录用户详细信息: {}", userService.getCurrentUser());
        } else {
            log.info("当前用户未登录或使用默认用户信息");
        }
        
        return ResponseResult.okResult(roleService.getPageList(page, limit, params));
    }

    /**
     * 根据ID获取角色
     */
    @GetMapping("/get/{id}")
    public ResponseResult getById(@PathVariable Long id) {
        return ResponseResult.okResult(roleService.getById(id));
    }

    /**
     * 保存角色
     */
    @PostMapping("/save")
    public ResponseResult save(@RequestBody Role role) {
        boolean result = roleService.saveRole(role);
        return result ? ResponseResult.okResult() : ResponseResult.errorResult(500, "保存失败");
    }

    /**
     * 更新角色
     */
    @PutMapping("/update")
    public ResponseResult update(@RequestBody Role role) {
        boolean result = roleService.updateRole(role);
        return result ? ResponseResult.okResult() : ResponseResult.errorResult(500, "更新失败");
    }

    /**
     * 删除角色
     */
    @DeleteMapping("/remove/{id}")
    public ResponseResult remove(@PathVariable Long id) {
        boolean result = roleService.removeRole(id);
        return result ? ResponseResult.okResult() : ResponseResult.errorResult(500, "删除失败");
    }

    /**
     * 批量删除角色
     */
    @DeleteMapping("/batchRemove")
    public ResponseResult batchRemove(@RequestBody Long[] ids) {
        boolean result = roleService.batchRemoveRoles(ids);
        return result ? ResponseResult.okResult() : ResponseResult.errorResult(500, "批量删除失败");
    }
}